<script>
/* 
    上传一张图片
 */
import { defineComponent } from 'vue'
export default defineComponent({
	name: 'Upload'
})
</script>
<script setup>
import { ref, defineExpose } from 'vue'
import { baseConfig } from '@/config'
import { useAuth } from '@/hooks'
const isRefresh = ref(true)
const videoUrl = ref('')
const url = '/wework/media/uploadfile'
const props = defineProps({
	imgurl: {
		type: String,
		default: ''
	},
	groupId: {
		type: Number,
		default: ''
	},
	// 1: 图片 2:视频 3:语音 4:混剪 5:文本, 默认1
	type: {
		type: Number,
		default: 1
	},
	isBtn: {
		type: Boolean,
		default: false
	},
	isBtn: {
		type: Boolean,
		default: false
	},
	btnWords: {
		type: String,
		default: '上传视频素材'
	}
})
const { state } = useAuth()

let headers = {
	'UserToken': state.token,
	// 'UserToken': '1f391c6c-51d9-11ed-8dd2-00163e2292ca',
}
// 没有token的处理
if(!state.token){
	// window.location.href = 'https://qiye.3yu.top/app/base/user?token=sdfsdfsdf'
	// headers = {
	// // 'UserToken': state.token,
	// 'UserToken': '1f391c6c-51d9-11ed-8dd2-00163e2292ca',
	// }
}
const data = {
	groupid: props.groupId
}
console.log(props.imgurl)
const imgurlRef = ref(props.imgurl)
// const headers = {
// 	'UserToken':'1f391c6c-51d9-11ed-8dd2-00163e2292ca'
// }
const handleSuccess = (res, uploadFile) => {
	// imgurlRef.value = URL.createObjectURL(uploadFile.raw)
	console.log(res.data, '上传成功后的urlstring')
	if (props.type == 2 && res.data.oss_type == 1) {
		// 获取封面
		getCover(res.data)
	} else {
		emits('getImg', res.data)
	}
}
const getCover = (obj) => {
	console.log(obj, '67867867867')
	videoUrl.value = obj.url
	const video = document.getElementById("upvideo"); // 获取视频对象
      // const video = document.createElement("video") // 也可以自己创建video
      video.src = url; // url地址 url跟 视频流是一样的
      var canvas = document.getElementById("mycanvas"); // 获取 canvas 对象
      const ctx = canvas.getContext("2d"); // 绘制2d
      video.crossOrigin = "anonymous"; // 解决跨域问题，也就是提示污染资源无法转换视频
      video.currentTime = 1; // 第一帧
      video.oncanplay = () => {
        canvas.width = video.clientWidth; // 获取视频宽度
        canvas.height = video.clientHeight; //获取视频高度
        // 利用canvas对象方法绘图
        ctx.drawImage(video, 0, 0, video.clientWidth, video.clientHeight);
        // 转换成base64形式
				let blob = dataURLToBlob(canvas.toDataURL("image/png")); // 截取后的视频封面
				pcmsImgUpload(blob).then(async(res) => {
					console.log(res.data.url,'78980980890890')
					const r = await reqUploadcover(
						{
							id:obj.id,
							cover:res.data.url
						}
					)
					if (r){
							// 绑定视频和图片
						emits('getImg',res.data)
					}
				
        })


}
}
const dataURLToBlob = (dataurl) => {
	console.log('datayutl')
	let arr = dataurl.split(',')
	let mime = arr[0].match(/:(.*?);/)[1]
	let bstr = atob(arr[1])
	let n = bstr.length
	let u8arr = new Uint8Array(n)
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n)
	}
	return new Blob([u8arr], {
		type: mime
	})
}
const pcmsImgUpload = (blob) => {
	return new Promise((resolve) => {
		var param = new window.FormData()
		// let config = {
		//   'X-SHOP-ADMIN-TOKEN': localStorage.getItem(tokenName4Shop),
		// }
		param.append('file', blob)
		;(async () => {
			const res = await upload(param)
			if (res.code === 200) {
				resolve(res.data)
			}
		})()
	})
}

const beforeUpload = (rawFile) => {
	if (props.type == 1) {
		if (rawFile.type.indexOf('image') == -1) {
			ElMessage.error('请上传图片')
			return false
		} else if (rawFile.size / 1024 / 1024 > 10) {
			ElMessage.error(' picture size can not exceed 10MB!')
			return false
		}
	} else if (props.type == 2) {
		console.log(rawFile.type, 'yguiyuiyu')
		if (rawFile.type.indexOf('image') != -1) {
			ElMessage.error('请上传视频')
			return false
		} else if (rawFile.size / 1024 / 1024 > 200) {
			ElMessage.error(' picture size can not exceed 200MB!')
			return false
		}
	} else if (props.type == 3) {
		console.log(rawFile.type, '11yguiyuiyu')
		if (rawFile.type.indexOf('audio') == -1) {
			ElMessage.error('请上传音频')
			return false
		} else if (rawFile.size / 1024 / 1024 > 200) {
			ElMessage.error(' picture size can not exceed 200MB!')
			return false
		}
	}else if (props.type == 4) {
		console.log(rawFile.type, '11yguiyuiyu')
		if (rawFile.type.indexOf('pdf') == -1) {
			ElMessage.error('请上传pdf文件')
			return false
		} else if (rawFile.size / 1024 / 1024 > 200) {
			ElMessage.error(' picture size can not exceed 200MB!')
			return false
		}
	}

	return true
}
const emits = defineEmits(['getImg'])

</script>
<template>
	<div>
		<video :src="videoUrl" style="width: 320px; height: 200px; display: none" controls="controls" id="upvideo"></video>
		<canvas id="mycanvas" style="display: none"></canvas>
		<el-upload
			:class="!isBtn ? 'uploader' : 'uploaderBtn'"
			:action="url"
			:headers="headers"
			:data="data"
			:show-file-list="false"
			:on-success="handleSuccess"
			:before-upload="beforeUpload"
		>
			<div class="button-small flex center" v-if="isBtn">
				<el-icon style="margin-right: 5px" size="22px"><FolderAdd /></el-icon>{{ btnWords }}
			</div>
			<img v-else-if="imgurlRef" :src="imgurlRef" class="upload-img" />
			<i v-else class="upload-icon el-icon-plus">
				<span style="position: absolute; font-size: 100px; top: -10px; right: 56px">+</span>
			</i>
		</el-upload>
	</div>
</template>
<style>
.uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.uploaderBtn .el-upload {
	border: none;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.uploader .el-upload:hover {
	border-color: #409eff;
}
.uploaderBtn .el-upload:hover {
	border: none;
}
.upload-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}
.upload-img {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
